﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.ServiceModel;

namespace YTV.MUpL
{
    public partial class EditXmlConfigDialog : Form
    {
        DataSet ds;
        BindingSource bs;
        public DataTable CurDt;
        public List<string> TN = new List<string>() {"ADD","REMOVE"};
        bool bCancel = true;
        TabPage tp;
        bool bInitEnded = false;
        bool IsFileChanged = false;
        public EditXmlConfigDialog(DataSet ds, BindingSource bs)
        {
            InitializeComponent();
            this.ds = ds;
            this.bs = bs;
            tp = tabContr.SelectedTab;
            cbConfigXMLFiles.DataSource = CompReadUpdateConfigFile.staticReadUpdateApplConfigFile.ListFiles;
        }


        private void cbListTables_SelectedValueChanged(object sender, EventArgs e)
        {
            if (bInitEnded && !IsFileChanged)
            {
                TN.Insert(0, cbListTables.Text);
                SetGrid();
            }
        }

        private void btOK_Click_1(object sender, EventArgs e)
        {
            if (bs != null && ds != null)
            {
                if (ds.Tables.Count != 0)
                {
                    bs.EndEdit();
                    ds.AcceptChanges();
                }
            }
            Close();
            bCancel = false;
        }

        private void btCancel_Click(object sender, EventArgs e)
        {
            Close();
            CurDt = null;
        }

        private void EditXmlConfigDialog_FormClosed(object sender, FormClosedEventArgs e)
        {
            ds = null;
            bs = null;
            if (bCancel)
                CurDt = null;
        }
        private void SetGrid()
        {
            string curN = "";
            CurDt= null;
            dgrTable.DataSource = null;
            dgrTable.Rows.Clear();
            dgrTable.Columns.Clear();
            if (IsFileChanged)
            {
                cbListTables.Items.Clear();
                cbListTables.Text = "";
            }
            if (ds != null)
            {
                foreach (string tn in TN)
                {
                    foreach (DataTable dt in ds.Tables)
                    {
                        if (IsFileChanged)
                        {
                            cbListTables.Items.Add(dt.TableName.ToUpper());
                        }
                        if (CurDt == null)
                        {                            
                                if (tn.Equals(dt.TableName, StringComparison.OrdinalIgnoreCase))
                                {
                                    CurDt = dt;
                                    curN = dt.TableName.ToUpper();
                                    
                                }
                            
                        }
                    }
                }
                if (CurDt == null && ds.Tables.Count > 0)
                {
                    CurDt = ds.Tables[0];
                    cbListTables.Text = ds.Tables[0].TableName.ToUpper();
                    TN.Insert(0, cbListTables.Text);
                }
                else
                {
                    cbListTables.Text=curN;
                }
                if (CurDt != null)
                {
                        if (bs == null)
                            bs = new BindingSource();
                        bs.DataSource = CurDt;
                        dgrTable.DataSource = bs;
                }

                
            }
            IsFileChanged = false;
        }
        private void EditXmlConfigDialog_Load(object sender, EventArgs e)
        {
            SetGrid();
            if (ds != null)
            {
                if (ds.Tables.Count == 0)
                {                    
                    if (cbConfigXMLFiles.Items.Count > 0)
                    {
                        if (CompReadUpdateConfigFile.staticReadUpdateApplConfigFile.MUplInpFilePath == null || !File.Exists(CompReadUpdateConfigFile.staticReadUpdateApplConfigFile.MUplInpFilePath))
                        {
                            CompReadUpdateConfigFile.staticReadUpdateApplConfigFile.MUplInpFilePath = cbConfigXMLFiles.Items[0].ToString();
                        }
                        cbConfigXMLFiles.Text = CompReadUpdateConfigFile.staticReadUpdateApplConfigFile.MUplInpFilePath;
                        CompReadUpdateConfigFile.staticReadUpdateApplConfigFile.LoadXML();
                        SetGrid();
                    }
                }
                else
                {
                    cbListTables.Text = TN[0];
                    cbConfigXMLFiles.Text = CompReadUpdateConfigFile.staticReadUpdateApplConfigFile.MUplInpFilePath;
                    //CompReadUpdateConfigFile.staticReadUpdateApplConfigFile.LoadXML();
                    //SetGrid();
                }
            }
            else
            {
                
                if (cbConfigXMLFiles.Items.Count > 0)
                {
                    if (CompReadUpdateConfigFile.staticReadUpdateApplConfigFile.MUplInpFilePath == null || !File.Exists(CompReadUpdateConfigFile.staticReadUpdateApplConfigFile.MUplInpFilePath))
                    {
                        CompReadUpdateConfigFile.staticReadUpdateApplConfigFile.MUplInpFilePath = cbConfigXMLFiles.Items[0].ToString();
                    }
                    cbConfigXMLFiles.Text = CompReadUpdateConfigFile.staticReadUpdateApplConfigFile.MUplInpFilePath;
                    CompReadUpdateConfigFile.staticReadUpdateApplConfigFile.LoadXML();
                    SetGrid();
                }
                else
                {
                    cbListTables.Text = "Configuration and XML File(s) is/are Empty or Absent";
                }
            }
            bInitEnded = true;
        }
        void uploadStreamWithProgress_ProgressChanged(object sender, StreamFileWithProgress.ProgressChangedEventArgs e)
        {
            if (e.Length != 0)
                progressBar1.Value = (int)(e.BytesRead * 100 / e.Length);
        }

        private void BrowseButton_Click(object sender, EventArgs e)
        {
            openFileDialog1.FileName = FileTextBox.Text;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                FileTextBox.Text = openFileDialog1.FileName;
            }
        }
        private void LogText(string text)
        {
            LogListBox.Items.Add(text);
            LogListBox.SelectedIndex = LogListBox.Items.Count - 1;
        }
        private void UploadButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            try
            {
                // get some info about the input file
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(FileTextBox.Text);

                // show start message
                LogText("Starting uploading " + fileInfo.Name);
                LogText("Size : " + fileInfo.Length);

                // open input stream
                using (System.IO.FileStream stream = new System.IO.FileStream(FileTextBox.Text, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    using (StreamFileWithProgress uploadStreamWithProgress = new StreamFileWithProgress(stream))
                    {
                        uploadStreamWithProgress.ProgressChanged += uploadStreamWithProgress_ProgressChanged;

                        // start service client
                        YTV.MUpL.FileTransferServiceClient client = new YTV.MUpL.FileTransferServiceClient();

                        // upload file
                        client.UploadFile(fileInfo.Name, fileInfo.Length, uploadStreamWithProgress);

                        LogText("Done!");

                        // close service client
                        client.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                LogText("Exception : " + ex.Message);
                if (ex.InnerException != null) LogText("Inner Exception : " + ex.InnerException.Message);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void DownloadButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            try
            {
                // start service client
                YTV.MUpL.FileTransferServiceClient client = new YTV.MUpL.FileTransferServiceClient();

                LogText("Start Download");

                // kill target file, if already exists
                //string filePath = tbDownloadFN.Text;
                //if (System.IO.File.Exists(filePath)) 
                    //System.IO.File.Delete(filePath);
                string filePath = System.IO.Directory.GetCurrentDirectory();
                filePath += System.IO.Path.GetFileName(tbDownloadFN.Text);
                if (System.IO.File.Exists(filePath)) 
                    System.IO.File.Delete(filePath);
                // get stream from server
                System.IO.Stream inputStream;
                string fileName = tbDownloadFN.Text;
                long length = client.DownloadFile(ref fileName, out inputStream);

                // write server stream to disk
                using (System.IO.FileStream writeStream = new System.IO.FileStream(filePath, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write))
                {
                    int chunkSize = 2048;
                    byte[] buffer = new byte[chunkSize];

                    do
                    {
                        // read bytes from input stream
                        int bytesRead = inputStream.Read(buffer, 0, chunkSize);
                        if (bytesRead == 0) break;

                        // write bytes to output stream
                        writeStream.Write(buffer, 0, bytesRead);

                        // report progress from time to time
                        progressBar1.Value = (int)(writeStream.Position * 100 / length);
                    } while (true);

                    // report end of progress
                    LogText("Done!");

                    writeStream.Close();
                }

                // close service client
                inputStream.Dispose();
                client.Close();
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                //string erri = ex.InnerException.Message;
                LogText("Exception : " + ex.Message);
                if (ex.InnerException != null) LogText("Inner Exception : " + ex.InnerException.Message);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void btBrouseDownload_Click(object sender, EventArgs e)
        {
            openFileDialog1.FileName = tbDownloadFN.Text;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                tbDownloadFN.Text = openFileDialog1.FileName;
            }
        }

        private void evTabIndexChanged(object sender, EventArgs e)
        {      
            
            if (tabContr.SelectedTab == tabFTP)
            {
                FtpForm ftpf = new FtpForm();
                ftpf.ShowDialog();
                tabContr.SelectTab(tabContr.TabPages.IndexOfKey(tp.Name));
            }
            tp = tabContr.SelectedTab;
        }

        private void cbFilesList_SelIndChanged(object sender, EventArgs e)
        {
            
            if (bInitEnded)
            {
                CompReadUpdateConfigFile.staticReadUpdateApplConfigFile.MUplInpFilePath = cbConfigXMLFiles.Text;
                CompReadUpdateConfigFile.staticReadUpdateApplConfigFile.LoadXML();
                IsFileChanged = true;
                SetGrid();
            }
            
        }

        private void btApply_Click(object sender, EventArgs e)
        {
            if (bs != null && ds != null)
            {
                if (ds.Tables.Count != 0)
                {
                    bs.EndEdit();
                    ds.AcceptChanges();
                }
            }
        }
    }
}
